package com.xhj.bigfactory.bigFactory.Lock;

import java.util.concurrent.locks.ReentrantLock;
/**
 * -
 *
 * @author 周沫 @Date 2021-07-25 @Time 23:23
 */
public class ReentrantLockDemo {
  public static void main(String[] args) {
    DataLD data = new DataLD();
    for (int i = 0; i < 12; i++) {
      new Thread(
              () -> {
                System.out.println(Thread.currentThread().getName() + " come in...");
                for (int j = 0; j < 100; j++) {
                  data.addPlusPlus();
                }
              },
              "t" + i)
          .start();
    }
    while (Thread.activeCount() > 2) {
      Thread.yield();
    }
    System.out.println("data.number = ================" + data.number);
    for (int i = 0; i < 4; i++) {
      new Thread(
              () -> {
                try {
                  Thread.sleep(500);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " come in...");
                data.dec();
              },
              "t" + i)
          .start();
    }
    while (Thread.activeCount() > 2) {
      Thread.yield();
    }
    System.out.println(" =============================================== ");
    new Thread(
            () -> {
              System.out.println(Thread.currentThread().getName() + " come in...");
              data.ddd();
            },
            "FFF")
        .start();
    new Thread(
            () -> {
              System.out.println(Thread.currentThread().getName() + " come in...");
              data.ddd();
            },
            "SSS")
        .start();
    new Thread(
            () -> {
              System.out.println(Thread.currentThread().getName() + " come in...");
              data.ddd();
            },
            "KKK")
        .start();
  }
}

class DataLD {
  ReentrantLock lock = new ReentrantLock();
  volatile int number = 0; // - - - - - 多线程不可见

  public void addPlusPlus() {
    lock.lock();
    try {
      number++;
      System.out.println("lock BBB ");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void dec() {
    lock.lock();
    try {
      System.out.println("lock AAA ");
      addPlusPlus();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void ddd() {
    lock.lock();
    lock.lock();
    try {
      System.out.println("FFF ====   ");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
      lock.unlock();
    }
  }
}
